package com.zhuangjie.mvc.validator.handler;

import com.zhuangjie.mvc.validator.annotate.ValidNumberEnumsString;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

public class ValidNumberEnumsStringValidator implements ConstraintValidator<ValidNumberEnumsString, String> {
    private ValidNumberEnumsString validNumberEnumsString;

    @Override
    public void initialize(final ValidNumberEnumsString constraintAnnotation) {
        validNumberEnumsString = constraintAnnotation; // 获取自定义分隔符
    }

    @Override
    public boolean isValid(final String value, final ConstraintValidatorContext context) {
        if (value == null || value.isEmpty()) {
            return true;
        }
        try {
            return Arrays.stream(value.split(validNumberEnumsString.delimiter()))
                    .mapToDouble(Double::valueOf)
                    .noneMatch(item -> !validNumberEnumsString.allowNegative() && item < 0);
        } catch (NumberFormatException e) {
            return false;
        }
    }
}